package com.eastedu.template.core.generator;

import com.eastedu.exception.ServiceException;
import com.eastedu.report.client.file.FileUploadService;
import com.eastedu.report.common.util.FileUtil;
import com.eastedu.template.core.render.ReportRender;
import com.eastedu.template.model.ReportDataContainer;
import com.eastedu.template.model.ReportResult;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * The type Default report generator.
 *
 * @author superman
 */
@Slf4j
public class DefaultReportGenerator implements ReportGenerator {
    private final ReportRender reportRender;
    private final FileUploadService fileUploadService;

    /**
     * Instantiates a new Default report generator.
     *
     * @param reportRender      the report render
     * @param fileUploadService the file upload service
     */
    public DefaultReportGenerator(ReportRender reportRender, FileUploadService fileUploadService) {
        this.reportRender = reportRender;
        this.fileUploadService = fileUploadService;
    }

    @Override
    public ReportResult generate(ReportDataContainer container, InputStream template) {
        // some code
        String taskId = container.getTaskId();
        try {
            this.deleteTempFile(taskId);
            String filepath = reportRender.render(container, template);
            if (!container.isDebug()) {
                filepath = fileUploadService.upload(container.getFilePath(), new File(filepath));
            }
            log.debug("[{}]报告生成成功, 文件路径: {}", taskId, filepath);
            return ReportResult.builder()
                    .taskId(taskId)
                    .url(filepath)
                    .debug(container.isDebug())
                    .build();
        } catch (Exception e) {
            throw new ServiceException(e, "渲染报告失败");
        } finally {
            if (!container.isDebug()) {
                this.deleteTempFile(taskId);
            }
        }
    }

    private void deleteTempFile(String taskId) {
        try {
            FileUtil.deleteTempFile(taskId);
        } catch (IOException e) {
            log.warn("「{}」报告生成的临时文件删除失败: {}", taskId, e.getMessage());
        }
    }
}
